package com.authsphere.security.common.utils;

import com.authsphere.security.common.exception.ValidationAuthenticationException;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import org.hibernate.validator.HibernateValidator;

import java.util.Set;

/**
 * @program: tech4j
 * @description:
 * @author: YuKai Fan
 * @create: 2025/3/4 10:45
 **/
public class BeanValidator {

    private final static Validator validator = Validation.byProvider(HibernateValidator.class)
            .configure()
            .failFast(true)
            .buildValidatorFactory()
            .getValidator();

    public static void validateObject(Object object, Class<?>... groups) {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        constraintViolations.stream()
                .findFirst()
                .ifPresent(constraintViolation -> {
                    throw new ValidationAuthenticationException(constraintViolation.getMessage());
                });
    }

    public static ConstraintViolation<Object> validate(Object object, Class<?>... groups) {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        return constraintViolations.stream()
                .findFirst().orElse(null);
    }
}
